package gui.batches;

import java.util.Date;
import java.util.List;

import common.util.DateUtils;

import core.Container;
import core.Item;
import core.ItemFacade;
import core.Product;
import core.ProductFacade;
import core.exception.ModelException;

public class AddItemCommand implements Command {
	private Product _product;
	private Container _container;
	private int _count;
	private Date _entryDate;
	private List<Item> _addedItems;
	private boolean _productCreated;
	
	
	
	/**
	 * Construct an add item command object
	 * @param p The product of the new items
	 * @param c The container for the new items
	 * @param count The number of new items
	 * @param entryDate The entry date for the items.
	 * @param productCreated True if the product was created as part of this operation.
	 */
	public AddItemCommand(Product p, Container c, int count, Date entryDate, 
			boolean productCreated){
		
		_product = p;
		_container = c;
		_count = count;
		_entryDate = entryDate;
		_addedItems = null;
		_productCreated = productCreated;
	}

	@Override
	public void execute() throws ModelException {
		// first time add
		if (_addedItems == null){
			if (_productCreated)
				ProductFacade.instance().addProductToContainer(_product, _container);
			_addedItems = ItemFacade.instance().createItems(_product, _container, _count, 
					DateUtils.formatDate(_entryDate));
		}
		else{ // redo
			if (_productCreated)
				ProductFacade.instance().createProduct(_product,_container);
			ItemFacade.instance().addItems(_addedItems, _container);
		}

	}

	@Override
	public void undo() throws ModelException{
		assert(_addedItems != null); // can't undo if action hasn't been done.
		
		ItemFacade.instance().removeItemsFromSystem(_addedItems);
		if (_productCreated)
			ProductFacade.instance().removeProduct(_product);
		
		for (int i = _count; i > 0; i--) {
			ItemFacade.instance().decrementBarcode();
		}

	}

}
